package com.atbun.eduservice.controller;


import com.atbun.commonutils.JwtUtils;
import com.atbun.commonutils.R;
import com.atbun.commonutils.vo.UcenterMemberVo;
import com.atbun.eduservice.client.UcenterClient;
import com.atbun.eduservice.entity.EduComment;
import com.atbun.eduservice.service.EduCommentService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 评论 前端控制器
 * </p>
 *
 * @author testjava
 * @since 2020-05-06
 */
@RestController
@RequestMapping("/eduservice/eduComment")
public class EduCommentController {

    @Autowired
    private EduCommentService eduCommentService;

    @Autowired
    private UcenterClient ucenterClient;

    /**
     * 分页获取评论数据
     * @param page
     * @param limit
     * @return
     */
    @GetMapping("getCommentPage/{page}/{limit}")
    public R getCommentPage(@PathVariable long page,@PathVariable long limit, String courseId){
        Page<EduComment> pageParam = new Page<>(page,limit);
        QueryWrapper<EduComment> wrapper = new QueryWrapper<>();
//        wrapper.eq("course_id",courseId);
        wrapper.orderByDesc("gmt_create");

        this.eduCommentService.getCommentPage(pageParam,wrapper);
        List<EduComment> commentList = pageParam.getRecords();

        Map<String, Object> map = new HashMap<>();
        map.put("items", commentList);
        map.put("current", pageParam.getCurrent());
        map.put("pages", pageParam.getPages());
        map.put("size", pageParam.getSize());
        map.put("total", pageParam.getTotal());
        map.put("hasNext", pageParam.hasNext());
        map.put("hasPrevious", pageParam.hasPrevious());
        return R.ok().data(map);
    }

    /**
     * 添加评论功能
     * request为什么可以得到用户id：
     *      因为在前端做了拦截，如果用户登录了，就把信息放到cookie的headers头信息中，
     * @param eduComment
     * @return
     */
    @PostMapping("saveCommentInfo")
    public R saveCommentInfo(@RequestBody EduComment eduComment, HttpServletRequest request){
//        根据请求获取会员id
        String memberId = JwtUtils.getMemberIdByJwtToken(request);
//        先判断用户是否登录
        if(StringUtils.isEmpty(memberId)) {
            return R.error().code(28004).message("请登录");
        }
        eduComment.setMemberId(memberId);

//        根据会员id得到会员(用户)信息
        UcenterMemberVo ucenterInfoPro = this.ucenterClient.getUcenterInfo(memberId);

        eduComment.setNickname(ucenterInfoPro.getNickname());
        eduComment.setAvatar(ucenterInfoPro.getAvatar());
        this.eduCommentService.save(eduComment);
        return R.ok();
    }

}

